const {
	Controller
} = require("uni-cloud-router");
const {
	success,
	fail,
	verify_token,
	build_token,
	create_uuid,
	encrypt,
	decrypt,
	isFieldExist,
	whereObj,
	isHttpMethod,
	isAdmin,
	isSuperAdmin,
	isAuthorities,

} = require('mh-utils');
//静态配置
const createConfig = require('uni-config-center')
const {
	count
} = require("console");
const envCfg = createConfig({
	pluginId: 'env'
}).config()

module.exports = class DictController extends Controller {
	//[sys:dict:list, sys:dict:add, sys:dict:update, sys:dict:delete]

	/**
	 * 初始化系统内置字典，创建新租户后调用。
	 */
	async initDict(newTenantId) {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		try {
			var where = '';
			where = whereObj({
				where,
				query: `tenantId=='${0}'`
			});
			where = whereObj({
				where,
				query: `deleted != 1`
			});
			var result = await dbJQL.collection("mh-sys-dictionary")
				.where(`${where}`)
				.get()
			if (result.data && result.data.length > 0) {
				var copyDict = result.data.map(item => {
						return {
							dictName: item.dictName,
							dictCode: item.dictCode,
							dictData: item.dictData,
							sortNumber: item.sortNumber,
							comments: item.comments,
							createUserId: `${ctx.auth.loginUserId}`,
							tenantId: newTenantId,
						}
					})
				await dbJQL.collection("mh-sys-dictionary")
					.add(copyDict)
			}
		} catch (e) {
			uniCloud.logger.error(e)
		}
	}

	/**
	 * 获取全部字典大项
	 */
	async list() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'GET')) {
			if (!isAdmin(ctx) && !isSuperAdmin(ctx)) {
				if (!isAuthorities(ctx, 'sys:dict:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try {
				var where = '';
				where = whereObj({
					where,
					query: `tenantId=='${ctx.auth.tenantId}'`
				});
				where = whereObj({
					where,
					query: `deleted != 1`
				});
				var sort = 'sortNumber';
				var order = 'asc';
				var result = await dbJQL.collection("mh-sys-dictionary")
					.where(`${where}`)
					.orderBy(`${sort}`, `${order}`)
					.get()
				if (result.data) {
					return success({
						code: 0,
						data: result.data.map(item => {
							return {
								...item,
								dictData: null
							}
						})
					})
				}
				return fail({
					code: 1,
				})
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 根据大项id，获取全部字典小项
	 */
	async listData() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'GET')) {
			if (!isAdmin(ctx) && !isSuperAdmin(ctx)) {
				if (!isAuthorities(ctx, 'sys:dict:list')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try {
				var result = await dbJQL.collection("mh-sys-dictionary")
					.doc(`${ctx.data._id}`)
					.get({
						getOne: true
					})
				if (result.data) {
					return success({
						code: 0,
						data: result.data.dictData || []
					})
				}
				return fail({
					code: 1,
				})
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	/**
	 * 根据大项code，获取全部字典小项
	 */
	async getDictDataByCode() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'GET')) {
			try {
				var result = await dbJQL.collection("mh-sys-dictionary")
					.where(`dictCode=='${ctx.data.dictCode}' && tenantId=="${ctx.auth.tenantId}"`)
					.get({
						getOne: true
					})
				if (result.data) {
					return success({
						code: 0,
						data: result.data.dictData || []
					})
				}
				return fail({
					code: 1,
				})
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}
	
	
	/**
	 * 根据大项id，添加字典小项
	 */
	async addDictData(){
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'POST')) {
			if (!isAdmin(ctx) && !isSuperAdmin(ctx)) {
				if (!isAuthorities(ctx, 'sys:dict:add')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try {
				var result = await dbJQL.collection("mh-sys-dictionary")
					.doc(`${ctx.data._id}`)
					.update({
						dictData: ctx.data.dictData,
						updateTime: new Date().getTime(),
					})
				if (result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				} else {
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 新增
	 * @example data
	 */
	async add() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'POST')) {
			if (!isAdmin(ctx) && !isSuperAdmin(ctx)) {
				if (!isAuthorities(ctx, 'sys:dict:add')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
			}
			try {
				delete ctx.data._id;
				var result = await dbJQL.collection("mh-sys-dictionary")
					.add({
						...ctx.data,
						"createUserId": ctx.auth.loginUserId,
						"tenantId": ctx.auth.tenantId,
					})
				if (result.id) {
					return success({
						code: 0,
						message: '操作成功'
					})
				} else {
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 修改
	 * @example data
	 */
	async update() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'PUT')) {
			if (!isAdmin(ctx) && !isSuperAdmin(ctx)) {
				if (!isAuthorities(ctx, 'sys:dict:update')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if (ctx.auth.loginUserId != ctx.data.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}
			try {
				var dictId = ctx.data._id;
				if (!dictId) return fail({
					code: 1,
					message: '参数无效'
				})
				delete ctx.data._id; //_id带到查询数据库会报错
				delete ctx.data.tenantId;
				var result = await dbJQL.collection("mh-sys-dictionary")
					.doc(dictId)
					.update({
						...ctx.data,
						updateTime: new Date().getTime()
					})
				if (result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				} else {
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}

	/**
	 * 删除
	 * @example ?_id=111111&&createUserId=2222222
	 */
	async remove() {
		const {
			ctx,
			service,
		} = this;
		const dbJQL = ctx.event.dbJQL;
		dbJQL.setUser({
			role: ['admin']
		})
		if (isHttpMethod(ctx, 'DELETE')) {
			if (!isAdmin(ctx) && !isSuperAdmin(ctx)) {
				if (!isAuthorities(ctx, 'sys:dict:delete')) {
					return fail({
						code: 1,
						message: '该用户无权限'
					})
				}
				if (ctx.auth.loginUserId != ctx.query.createUserId) {
					return fail({
						code: 1,
						message: '不可操作非本人数据'
					})
				}
			}

			try {
				var dictId = ctx.query._id;
				if (!dictId) return fail({
					code: 1,
					message: '参数无效'
				})
				//删除
				var result = await dbJQL.collection("mh-sys-dictionary")
					.doc(dictId)
					.update({
						deleted: 1,
						updateTime: new Date().getTime()
					})
				if (result.updated > 0) {
					return success({
						code: 0,
						message: '操作成功'
					})
				} else {
					return fail({
						code: 1,
						message: '操作失败'
					})
				}
			} catch (e) {
				uniCloud.logger.error(e)
				return fail({
					code: 500,
					data: e,
					message: e.errMsg
				})
			}
		}
	}


};
